#
# Unit tests for STemp
#
# STemp - Secure tempfile extension for Ruby
#
# Author:: Cian Synnott <cian@nospam@gmail.com>
# Copyright:: Copyright (c) 2006 Cian Synnott
# License:: MIT License
# 
# For license info, see the README file bundled with this package.
#
# $Id: ts_stemp.rb 6 2006-11-15 18:25:26Z cian $
#

require 'test/unit'
require 'fileutils'
require 'tmpdir'

require 'rubygems'
require 'stemp'

# Tests for STemp
class TestSTemp < Test::Unit::TestCase
  WRITE   = "#{Dir.tmpdir}/test-stemp-write"
  NOWRITE = "#{Dir.tmpdir}/test-stemp-nowrite"

  def setup
    # Create writeable and unwriteable directory 'fixtures'
    FileUtils.mkdir(WRITE, :mode => 0700)
    FileUtils.mkdir(NOWRITE, :mode => 0500)
  end

  # Tests for +mkdtemp+.
  def test_mkdtemp
    # If we're getting the correct EACCES exceptions here, the exception
    # handling in mkdtemp is working. Don't bother if we're root. :op
    unless Process.euid == 0
      dirname = "#{NOWRITE}/dir-XXXXXX"
      assert_raise(Errno::EACCES) { STemp.mkdtemp(dirname) }
    end

    # Normal behaviour. Remember to check side-effect.
    dirname = "#{WRITE}/dir-XXXXXX"
    newname = STemp.mkdtemp(dirname)
    assert_equal(newname, dirname)
    assert_not_equal(dirname, "#{WRITE}/dir-XXXXXX")
    assert(File.directory?(dirname))
  end

  # Tests for +mkstemp+.
  def test_mkstemp
    # See comments above on first assertion.
    unless Process.euid == 0
      filename = "#{NOWRITE}/file-XXXXXX"
      assert_raise(Errno::EACCES) { STemp.mkstemp(filename) }
    end

    # Test creating a file, writing to it etc. and that it exists at the end.
    filename = "#{WRITE}/file-XXXXXX"
    f = STemp.mkstemp(filename)
    assert_not_equal(filename, "#{WRITE}/file-XXXXXX")
    text = nil
    assert_nothing_raised do
      f.puts 'test string'
      f.rewind
      text = f.read
      f.close
    end
    assert_equal(text, "test string\n")
    assert(File.exists?(filename))
  end

  # Tests for +tmpfile+.
  def test_tmpfile
    # Test creating a file, writing to it etc.
    f = STemp.tmpfile
    text = nil
    assert_nothing_raised do
      f.puts 'test string'
      f.rewind
      text = f.read
      f.close
    end
    assert_equal(text, "test string\n")
  end

  def teardown
    FileUtils.rm_rf(WRITE)
    FileUtils.rm_rf(NOWRITE)
  end
end
